﻿using SnmpForm.FaultDetect;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace SnmpForm
{
    public partial class MainForm : Form
    {
        FrmAPManager _objFrmAPManager = null;
        ApSearch.FrmApSearch _objFrmApSearch = null;
        FrmSysConfig _objFrmSysConfig = null;
        SysUser.frmSysUserManager _objSysUserManager = null;
        FaultDetect.FrmFaultDetect _objFaultDetect = null;
        ApSysLog.FrmApSysLog _objApSysLog = null;
        FrmSystemLog _objFrmSystemLog = null;

        //ApIpPool检测线程
        public delegate void UpdateApIpPool(DbWrapper.DbDataTypes.Ap apinfo);
        public UpdateApIpPool updateApIpPool;
        public void UpdateApIpPoolMethod(DbWrapper.DbDataTypes.Ap apinfo)
        {
            //通过数据库查询
            BusinessWrapper.Ap ap = BusinessWrapper.User.Instance.GetAp(apinfo.mark);
            if (ap != null)
            {
                ApIpPool.ApIpPool.Instance.Update(ap.GetInfo().id, apinfo.manage_ip);
            }
            else
            {
                //发现新的未托管ap
                if (_objFrmApSearch!=null)
                {
                    _objFrmApSearch.Invoke(_objFrmApSearch.newApFinded, new Object[] { apinfo });
                }
            }
        }
        private Thread objThreadApIpPool = null;
        private ApIpPool.ApIpPoolTask taskApIpPool = null;

        public delegate void ApIpPoolTaskManager(string action);
        public ApIpPoolTaskManager apIpPoolTaskManager;
        public void ApIpPoolTaskManagerMethod(string action)
        {
            switch (action)
            {
                case "start":
                    StartApIpPoolTask();
                    break;
                case "stop":
                    StopApIpPoolTask();
                    break;
                case "restart":
                    RestartApIpPoolTask();
                    break;
                default:
                    break;
            }
        }
        private void StartApIpPoolTask()
        {
            if (objThreadApIpPool == null ||
                objThreadApIpPool.ThreadState == ThreadState.Stopped)
            {
                List<DbWrapper.DbDataTypes.SearchTarget> listTarget =
                    BusinessWrapper.User.Instance.GetApIpPoolSearchTargetList();
                if (listTarget != null)
                {
                    taskApIpPool = new ApIpPool.ApIpPoolTask(this, listTarget);
                    objThreadApIpPool = new Thread(taskApIpPool.TaskFunction);
                    objThreadApIpPool.Start();
                }
            }
            else
            {
                MessageBox.Show("任务正在运行");
            }
        }
        private void StopApIpPoolTask()
        {
            if (objThreadApIpPool != null)
            {
                if (objThreadApIpPool.ThreadState != ThreadState.Stopped)
                {

                    objThreadApIpPool.Abort();
                    objThreadApIpPool = null;
                }
            }
        }
        private void RestartApIpPoolTask()
        {
            BeginInvoke(apIpPoolTaskManager, "stop");
            BeginInvoke(apIpPoolTaskManager, "start");
        }


        //故障检测线程
        //创建一个委托，是为访问服务的。         
        public delegate void DetectFaultTaskManager(string action);
        //定义一个委托变量         
        public DetectFaultTaskManager detectFaultTaskManager;
        public void DetectFaultTaskManagerMethod(string action)
        {
            switch (action)
            {
                case "start":
                    StartCheckTask();
                    break;
                case "stop":
                    StopCheckTask();
                    break;
                case "restart":
                    RestartCheckTask();
                    break;
                default:
                    break;
            }
        }
        private Thread objThreadDetect = null;
        private DetectTask task = null;
        private void StartCheckTask()
        {
            if (objThreadDetect == null ||
                objThreadDetect.ThreadState == ThreadState.Stopped)
            {
                List<BusinessWrapper.Ap> listAsset =
                    BusinessWrapper.User.Instance.GetApList("");
                task = new DetectTask(this, listAsset);
                objThreadDetect = new Thread(task.ThreadFaultDetect);
                objThreadDetect.Start();
            }
            else
            {
                MessageBox.Show("任务正在运行");
            }
        }
        private void StopCheckTask()
        {
            if (objThreadDetect != null)
            {

                if (objThreadDetect.ThreadState != ThreadState.Stopped)
                {

                    objThreadDetect.Abort();
                    objThreadDetect = null;
                }
            }
        }
        private void RestartCheckTask()
        {
            BeginInvoke(detectFaultTaskManager, "stop");
            BeginInvoke(detectFaultTaskManager, "start");
        }

        //创建一个委托，是为访问服务的。         
        public delegate void UpdateViewFaultAp(FaultDetectEvent ev);
        //定义一个委托变量         
        public UpdateViewFaultAp updateViewFaultAp;
        public void UpdateViewFaultApMethod(FaultDetectEvent ev)
        {
            bool bModify = FaultDetect.DetectData.Instance.ModifyWithEvent(ev);
            if (bModify)
            {
                if (_objFaultDetect!=null)
                {
                    _objFaultDetect.ReloadViewFaultAp();
                }

                if (_objFrmAPManager != null)
                {
                    _objFrmAPManager.updateViewApFault();
                }
            }
        }

        public MainForm()
        {
            InitializeComponent();
            this.IsMdiContainer = true;
        }

        private void OpenApManage()
        {
            if (_objFrmAPManager == null || _objFrmAPManager.IsDisposed)
            {
                _objFrmAPManager = new FrmAPManager(this);
                _objFrmAPManager.MdiParent = this;
                _objFrmAPManager.WindowState = FormWindowState.Maximized;
                _objFrmAPManager.Show();
            }
            else
            {
                _objFrmAPManager.WindowState = FormWindowState.Maximized;
                _objFrmAPManager.Activate();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnManageAP_Click(object sender, EventArgs e)
        {
            OpenApManage();
        }

        private void ToolStripMenuItemApManage_Click(object sender, EventArgs e)
        {
            OpenApManage();
        }

        private void OpenApSearch()
        {
            if (_objFrmApSearch == null || _objFrmApSearch.IsDisposed)
            {
                _objFrmApSearch = new ApSearch.FrmApSearch(this);
                _objFrmApSearch.MdiParent = this;
                _objFrmApSearch.WindowState = FormWindowState.Maximized;
                _objFrmApSearch.Show();
            }
            else
            {
                _objFrmApSearch.WindowState = FormWindowState.Maximized;
                _objFrmApSearch.Activate();
            }
        }
        private void ToolStripMenuItemApSearch_Click(object sender, EventArgs e)
        {
            OpenApSearch();
        }

        private void btnApSearch_Click(object sender, EventArgs e)
        {
            OpenApSearch();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //屏蔽菜单栏
            menuStrip1.Visible = false;
            //用户登入
            bool bLogined = false;
            while(true){
                LoginForm login = new LoginForm();
                DialogResult result = login.ShowDialog();
                if(result == System.Windows.Forms.DialogResult.OK){
                    string strUsername = login.GetUsername();
                    string strPassword = login.GetPassword();
                    bool bSuccess = BusinessWrapper.User.Instance.Login(strUsername, strPassword);
                    if (bSuccess)
                    {
                        bLogined = true;
                        BusinessWrapper.User.Instance.Log(
                            DbWrapper.DbDataTypes.LogInfo.LEVEL.INFO,
                            DbWrapper.DbDataTypes.LogInfo.TYPE.SYSTEM,
                            "登入成功");
                        break;
                    }
                    else
                    {
                        MessageBox.Show("登入错误");
                        DbWrapper.SQLDataOperate.Instance.WriteMessage(
                            DbWrapper.DbDataTypes.LogInfo.LEVEL.WARMING,
                            DbWrapper.DbDataTypes.LogInfo.TYPE.USER,
                            strUsername + "登入失败");
                        continue;
                    }
                }
                else{
                    this.Close();
                }
                break;
            }

            if (bLogined)
            {
                //默认打开AP管理页面
                btnManageAP.Checked = true;
                btnManageAP_Click(null, null);

                bool bPrivilege = false;

                //AP日志
                //该功能暂时屏蔽
                ToolStripMenuItemApSysLog.Visible = bPrivilege;
                bntAPSyslog.Visible = bPrivilege;
                //AP搜索菜单权限
                bPrivilege = 
                    BusinessWrapper.User.Instance.Permision(BusinessWrapper.Types.Privilege.SearchAP.permision);
                ToolStripMenuItemApSearch.Visible = bPrivilege;
                btnApSearch.Visible = bPrivilege;

                //系统管理菜单权限
                bPrivilege =
                    BusinessWrapper.User.Instance.Permision(BusinessWrapper.Types.Privilege.SystemManage.permision);
                toolStripButtonSystemConfig.Visible = bPrivilege;
                ToolStripMenuItemSysConfig.Visible = bPrivilege;

                //系统设置菜单权限
                bPrivilege =
                    BusinessWrapper.User.Instance.Permision(BusinessWrapper.Types.Privilege.SystemManage.SystemConfig.permision);
                ToolStripMenuItemSystemManage.Visible = bPrivilege;
                //用户管理菜单权限
                bPrivilege =
                     BusinessWrapper.User.Instance.Permision(BusinessWrapper.Types.Privilege.SystemManage.SysUserManager.permision);
                ToolStripMenuItemSysUserManager.Visible = bPrivilege;
                toolStripButtonSysUserManage.Visible = bPrivilege;

                //AP异常检测委托
                updateViewFaultAp = new UpdateViewFaultAp(UpdateViewFaultApMethod);
                detectFaultTaskManager = 
                    new DetectFaultTaskManager(DetectFaultTaskManagerMethod);
                //开启故障检测线程
                StartCheckTask();

                //ApIpPool
                updateApIpPool = new UpdateApIpPool(UpdateApIpPoolMethod);
                apIpPoolTaskManager =
                    new ApIpPoolTaskManager(ApIpPoolTaskManagerMethod);
                StartApIpPoolTask();
            }
        }

        private void OpenSysConfig()
        {
            if (_objFrmSysConfig == null || _objFrmSysConfig.IsDisposed)
            {
                _objFrmSysConfig = new FrmSysConfig(this);
                _objFrmSysConfig.MdiParent = this;
                _objFrmSysConfig.WindowState = FormWindowState.Maximized;
                _objFrmSysConfig.Show();
            }
            else
            {
                _objFrmSysConfig.WindowState = FormWindowState.Maximized;
                _objFrmSysConfig.Activate();
            }
        }

        private void ToolStripMenuItemSysConfig_Click(object sender, EventArgs e)
        {
            OpenSysConfig();
        }

        /// <summary>
        /// 点击系统配置按钮弹出窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSysConfig_Click(object sender, EventArgs e)
        {
            OpenSysConfig();
        }

        private void OpenSysUsermanager()
        {
            if (_objSysUserManager == null || _objSysUserManager.IsDisposed)
            {
                _objSysUserManager = new SysUser.frmSysUserManager();
                _objSysUserManager.MdiParent = this;
                _objSysUserManager.WindowState = FormWindowState.Maximized;
                _objSysUserManager.Show();
            }
            else
            {
                _objSysUserManager.WindowState = FormWindowState.Maximized;
                _objSysUserManager.Activate();
            }
        }
        private void ToolStripMenuItemSysUserManager_Click(object sender, EventArgs e)
        {
            OpenSysUsermanager();
        }

        private void toolStripButtonSysUserManage_Click(object sender, EventArgs e)
        {
            OpenSysUsermanager();
        }

        private void OpenAbout()
        {
            Form dl = new FrmAbout();
            dl.ShowDialog();
        }
        private void ToolStripMenuItemAbout_Click(object sender, EventArgs e)
        {
            OpenAbout();
        }

        private void toolStripButtonAbout_Click(object sender, EventArgs e)
        {
            OpenAbout();
        }

        private void OpenFaultDetect()
        {
            if (_objFaultDetect == null || _objFaultDetect.IsDisposed)
            {
                _objFaultDetect = new FaultDetect.FrmFaultDetect();
                _objFaultDetect.MdiParent = this;
                _objFaultDetect.WindowState = FormWindowState.Maximized;
                _objFaultDetect.Show();
            }
            else
            {
                _objFaultDetect.WindowState = FormWindowState.Maximized;
                _objFaultDetect.Activate();
            }
        }

        private void btnAPFault_Click(object sender, EventArgs e)
        {
            OpenFaultDetect();
        }

        private void ToolStripMenuItemFaultDetect_Click(object sender, EventArgs e)
        {
            OpenFaultDetect();
        }

        private void OpenApSysLog()
        {
            if (_objApSysLog == null || _objApSysLog.IsDisposed)
            {
                _objApSysLog = new ApSysLog.FrmApSysLog();
                _objApSysLog.MdiParent = this;
                _objApSysLog.WindowState = FormWindowState.Maximized;
                _objApSysLog.Show();
            }
            else
            {
                _objApSysLog.WindowState = FormWindowState.Maximized;
                _objApSysLog.Activate();
            }
        }

        private void bntAPSyslog_Click(object sender, EventArgs e)
        {
            OpenApSysLog();
        }

        private void ToolStripMenuItemApSysLog_Click(object sender, EventArgs e)
        {
            OpenApSysLog();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //关闭检测线程
            StopCheckTask();
            StopApIpPoolTask();
        }

        private void OpenSystemLog()
        {
            if (_objFrmSystemLog == null || _objFrmSystemLog.IsDisposed)
            {
                _objFrmSystemLog = new FrmSystemLog(this);
                _objFrmSystemLog.MdiParent = this;
                _objFrmSystemLog.WindowState = FormWindowState.Maximized;
                _objFrmSystemLog.Show();
            }
            else
            {
                _objFrmSystemLog.WindowState = FormWindowState.Maximized;
                _objFrmSystemLog.Activate();
            }
        }

        private void toolStripButtonSystemLog_Click(object sender, EventArgs e)
        {
            OpenSystemLog();
        }

        private void ToolStripMenuItemSystemLog_Click(object sender, EventArgs e)
        {
            OpenSystemLog();
        }

        private void toolStripButtons_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem != toolStripButtonAbout)
            {
                foreach (ToolStripButton button in toolStripButtons.Items)
                {
                    if (button == e.ClickedItem)
                    {
                        button.Checked = true;
                    }
                    else
                    {
                        button.Checked = false;
                    }
                }
            }
            else
            {
                //如果选中的是关于按钮，则不进行选中变更
            }
        }
    }
}
